package com.yosaa.back.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yosaa.back.entity.AnalysisResult;
import com.yosaa.back.entity.UserInfo;
import com.yosaa.back.service.IAnalysisResultService;
import com.yosaa.back.service.IUsersService;
import com.yosaa.back.utils.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 分析结果表，存储AI分析模块生成的健康评估和个性化建议 前端控制器
 * </p>
 *

 */
@RestController
@RequestMapping("/analysis-result")
public class AnalysisResultController {

    @Autowired
    private IAnalysisResultService analysisResultService;
    @Autowired
    private IUsersService usersService;

    @GetMapping("/list")
    public ResponseEntity getAnalysisResultList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer userId,
            @RequestParam(required = false) String analysisDate) {

        Page<AnalysisResult> resultPage = new Page<>(page, size);

        QueryWrapper<AnalysisResult> queryWrapper = new QueryWrapper<>();
        if (userId != null) {
            queryWrapper.eq("user_id", userId);
        }
        if (analysisDate != null && !analysisDate.trim().isEmpty()) {
            queryWrapper.eq("analysis_date", analysisDate);
        }

        Integer currentUserId = StpUtil.getLoginIdAsInt();
        UserInfo userInfo = usersService.getById(currentUserId);
        if (!userInfo.getRole().equals("admin")) {
            queryWrapper.eq("user_id", currentUserId);
            IPage<AnalysisResult> result = analysisResultService.page(resultPage, queryWrapper);
            result.getRecords().forEach(result1 -> result1.setUserName(usersService.getById(result1.getUserId()).getUsername()));
            return ResponseEntity.ok(new ApiResponse(0, result, "操作成功"));
        }

        IPage<AnalysisResult> result = analysisResultService.page(resultPage, queryWrapper);
        result.getRecords().forEach(result1 -> result1.setUserName(usersService.getById(result1.getUserId()).getUsername()));
        return ResponseEntity.ok(new ApiResponse(0, result, "操作成功"));
    }

    @PostMapping("/add")
    public ResponseEntity<ApiResponse> addAnalysisResult(@RequestBody AnalysisResult analysisResult) {
        boolean saved = analysisResultService.save(analysisResult);
        if (saved) {
            return ResponseEntity.ok(new ApiResponse(0, null, "操作成功"));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(1, null, "操作失败"));
        }
    }

    @PostMapping("/update")
    public ResponseEntity<ApiResponse> updateAnalysisResult(@RequestBody AnalysisResult analysisResult) {
        boolean updated = analysisResultService.updateById(analysisResult);
        if (updated) {
            return ResponseEntity.ok(new ApiResponse(0, null, "操作成功"));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(1, null, "操作失败"));
        }
    }

    @GetMapping("/get/{id}")
    public ResponseEntity<ApiResponse> getAnalysisResult(@PathVariable Integer id) {
        AnalysisResult analysisResult = analysisResultService.getById(id);
        if (analysisResult != null) {
            return ResponseEntity.ok(new ApiResponse(0, analysisResult, "操作成功"));
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse(1, null, "操作失败"));
        }
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity<ApiResponse> deleteAnalysisResult(@PathVariable Integer id) {
        boolean deleted = analysisResultService.removeById(id);
        if (deleted) {
            return ResponseEntity.ok(new ApiResponse(0, null, "操作成功"));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(1, null, "操作失败"));
        }
    }

    @GetMapping("/ai")
    public ResponseEntity getAiData(@RequestParam("userId") Integer userId) {
        analysisResultService.aiAnalysis(userId);

        return ResponseEntity.ok(new ApiResponse(0, null, "操作成功"));
    }
}
